<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>交易流水</p>
		</header>

		<!-- 筛选条件 -->
		<div class="filter-section">
			<div class="filter-group">
				<label>交易类型:</label>
				<select v-model="selectedType" @change="loadTransactions">
					<option value="">全部</option>
					<option value="RECHARGE">充值</option>
					<option value="WITHDRAW">提现</option>
					<option value="PAYMENT">支付</option>
					<option value="RECEIVED">被支付</option>
					<option value="FREEZE">冻结</option>
					<option value="UNFREEZE">解冻</option>
					<option value="OVERDRAFT">透支</option>
					<option value="REPAYMENT">还款</option>
				</select>
			</div>

			<div class="filter-group">
				<label>时间范围:</label>
				<select v-model="selectedTimeRange" @change="loadTransactions">
					<option value="7">近7天</option>
					<option value="30">近30天</option>
					<option value="90">近90天</option>
					<option value="custom">自定义</option>
				</select>
			</div>

			<!-- 自定义时间选择 -->
			<div class="custom-date" v-if="selectedTimeRange === 'custom'">
				<div class="date-group">
					<label>开始日期:</label>
					<input type="date" v-model="startDate" @change="loadTransactions">
				</div>
				<div class="date-group">
					<label>结束日期:</label>
					<input type="date" v-model="endDate" @change="loadTransactions">
				</div>
			</div>
		</div>

		<!-- 交易列表 -->
		<div class="transactions-list" v-if="!isLoading && transactions.length > 0">
			<div
				v-for="transaction in transactions"
				:key="transaction.id"
				class="transaction-item"
				@click="showTransactionDetail(transaction)"
			>
				<div class="transaction-header">
					<span class="transaction-type">{{ getTransactionTypeText(transaction.transactionType) }}</span>
					<span class="transaction-time">{{ formatDateTime(transaction.transactionTime) }}</span>
				</div>
				<div class="transaction-content">
					<div class="amount-section">
						<span
							class="amount"
							:class="{
								'income': transaction.amount > 0,
								'expense': transaction.amount < 0
							}"
						>
							{{ transaction.amount > 0 ? '+' : '' }}¥{{ Math.abs(transaction.amount).toFixed(2) }}
						</span>
					</div>
					<div class="transaction-info">
						<p class="remark" v-if="transaction.remark">{{ transaction.remark }}</p>
						<p class="order-info" v-if="transaction.order">
							订单: {{ transaction.order.id }}
							<span v-if="transaction.transactionType === 'FREEZE' || transaction.transactionType === 'UNFREEZE'">
								- {{ getFreezeReason(transaction) }}
							</span>
						</p>
					</div>
				</div>
				<div class="transaction-arrow">
					<i class="fa fa-chevron-right"></i>
				</div>
			</div>
		</div>

		<!-- 空状态 -->
		<div class="empty-state" v-if="!isLoading && !errorMsg && transactions.length === 0">
			<i class="fa fa-list-alt"></i>
			<p>暂无交易记录</p>
			<button class="action-btn" @click="goToRecharge">去充值</button>
		</div>

		<!-- 加载状态 -->
		<div v-if="isLoading" class="loading">
			<p>加载中...</p>
		</div>

		<!-- 错误提示 -->
		<div v-if="errorMsg" class="error-msg" :class="{ 'backend-error': isBackendError }">
			<p>{{ errorMsg }}</p>
			<p v-if="isBackendError" class="error-tip">
				这是后端配置问题，需要后端开发人员修复Hibernate序列化配置。重试无法解决此问题。
			</p>
			<button v-if="!isBackendError" @click="loadTransactions(true)">重试</button>
		</div>

		<!-- 返回按钮 -->
		<div class="back-button">
			<button @click="goBack">返回</button>
		</div>

		<!-- 底部菜单 -->
		<Footer></Footer>
	</div>
</template>

<script>
import Footer from '../components/Footer.vue';
import axios from 'axios';

export default {
	name: 'WalletTransactions',
	components: {
		Footer
	},
	data() {
		return {
			selectedType: '',
			selectedTimeRange: '7',
			startDate: '',
			endDate: '',
			transactions: [],
			allTransactions: [], // 缓存所有交易记录
			isLoading: false,
			errorMsg: '',
			needReload: true, // 是否需要重新加载数据
			isBackendError: false // 是否是后端配置错误
		};
	},
	methods: {
		async loadTransactions(forceReload = false) {
			this.isLoading = true;
			this.errorMsg = '';
			try {
				// 如果需要重新加载或强制刷新，则从后端获取数据
				if (this.needReload || forceReload || this.allTransactions.length === 0) {
					const token = localStorage.getItem('id_token');
					if (!token) {
						this.$router.push('/login');
						return;
					}

					// 根据后端接口文档，不需要传递任何查询参数，直接获取所有交易记录
					const response = await axios.get('wallet/transactions', {
						headers: {
							'Authorization': `Bearer ${token}`
						},
						timeout: 10000 // 10秒超时
					});


					if (response.data && response.data.success && (response.data.code === 200 || response.data.code === 0)) {
						this.allTransactions = response.data.data || [];
						// 按时间倒序排列
						this.allTransactions.sort((a, b) => new Date(b.transactionTime) - new Date(a.transactionTime));
						this.needReload = false;
					} else {
						this.errorMsg = response.data?.message || '获取交易记录失败';
						this.isLoading = false;
						return;
					}
				}

				// 对缓存的数据进行筛选
				let filteredTransactions = [...this.allTransactions];
				
				// 客户端筛选：按交易类型
				if (this.selectedType) {
					filteredTransactions = filteredTransactions.filter(t => t.transactionType === this.selectedType);
				}
				
				// 客户端筛选：按时间范围
				if (this.selectedTimeRange && this.selectedTimeRange !== 'custom') {
					const now = new Date();
					const days = parseInt(this.selectedTimeRange);
					const startDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
					filteredTransactions = filteredTransactions.filter(t => {
						const transactionDate = new Date(t.transactionTime);
						return transactionDate >= startDate && transactionDate <= now;
					});
				} else if (this.selectedTimeRange === 'custom' && this.startDate && this.endDate) {
					const startDate = new Date(this.startDate);
					const endDate = new Date(this.endDate);
					endDate.setHours(23, 59, 59, 999);
					filteredTransactions = filteredTransactions.filter(t => {
						const transactionDate = new Date(t.transactionTime);
						return transactionDate >= startDate && transactionDate <= endDate;
					});
				}
				
				this.transactions = filteredTransactions;
			} catch (error) {
				if (error.response) {
					const status = error.response.status;
					const errorData = error.response.data;
					
					// 重置后端错误标志
					this.isBackendError = false;
					
					// 检查是否是Hibernate序列化错误
					if (errorData && errorData.message) {
						const errorMessage = errorData.message;
						// 检测Hibernate序列化错误
						if (errorMessage.includes('ByteBuddyInterceptor') || 
						    errorMessage.includes('Type definition error') ||
						    errorMessage.includes('Hibernate') ||
						    errorMessage.includes('Jackson') ||
						    errorMessage.includes('serialization') ||
						    errorMessage.includes('Could not write JSON') ||
						    errorMessage.includes('com.fasterxml.jackson')) {
							this.isBackendError = true;
							this.errorMsg = '数据序列化错误，请联系管理员修复后端配置';
							// 设置空数组，避免页面崩溃
							this.transactions = [];
							this.allTransactions = [];
						} else if (status === 500) {
							// 500错误但错误信息不明确，也标记为后端错误
							this.isBackendError = true;
							this.errorMsg = `服务器内部错误（500）：${errorMessage || '请联系管理员检查后端日志'}`;
							// 设置空数组，避免页面崩溃
							this.transactions = [];
							this.allTransactions = [];
						} else {
							this.errorMsg = errorMessage;
						}
					} else if (status === 500) {
						// 500错误但没有详细错误信息
						this.isBackendError = true;
						this.errorMsg = '服务器内部错误（500），这通常是后端配置问题，请联系管理员检查后端日志';
						// 设置空数组，避免页面崩溃
						this.transactions = [];
						this.allTransactions = [];
					} else if (status === 401) {
						this.errorMsg = '登录已过期，请重新登录';
						this.$router.push('/login');
					} else if (status === 404) {
						this.errorMsg = '接口不存在，请联系管理员';
					} else {
						this.errorMsg = `获取交易记录失败 (${status})`;
					}
				} else if (error.code === 'ECONNABORTED') {
					this.errorMsg = '请求超时，请检查网络连接';
				} else {
					this.errorMsg = '网络错误，请重试';
				}
			} finally {
				this.isLoading = false;
			}
		},
		getTransactionTypeText(type) {
			const typeMap = {
				'RECHARGE': '充值',
				'WITHDRAW': '提现',
				'PAYMENT': '支付',
				'RECEIVED': '收款',
				'FREEZE': '冻结',
				'UNFREEZE': '解冻',
				'OVERDRAFT': '透支',
				'REPAYMENT': '还款'
			};
			return typeMap[type] || type;
		},
		formatDateTime(dateTime) {
			const date = new Date(dateTime);
			const now = new Date();
			const diff = now - date;
			const days = Math.floor(diff / (1000 * 60 * 60 * 24));

			if (days === 0) {
				return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
			} else if (days === 1) {
				return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
			} else if (days < 7) {
				return `${days}天前`;
			} else {
				return date.toLocaleDateString('zh-CN');
			}
		},
		getFreezeReason(transaction) {
			if (!transaction.order) return '';

			// 根据订单状态判断冻结原因
			const orderState = transaction.order.orderState;
			switch (orderState) {
				case 0: return '订单待确认';
				case 1: return '订单进行中';
				case 2: return '订单已完成';
				case 3: return '订单已取消';
				default: return '订单处理中';
			}
		},
		showTransactionDetail(transaction) {
			// 如果是冻结或解冻类型的交易，跳转到冻结详情页
			if (transaction.transactionType === 'FREEZE' || transaction.transactionType === 'UNFREEZE') {
				this.$router.push({
					path: '/walletFreezeDetail',
					query: { transactionId: transaction.id }
				});
			} else {
				// 其他类型的交易可以显示详情弹窗或页面
				// 这里暂时用alert展示，实际可以优化为弹窗组件
				alert(`交易详情：\n类型：${this.getTransactionTypeText(transaction.transactionType)}\n金额：¥${Math.abs(transaction.amount).toFixed(2)}\n时间：${this.formatDateTime(transaction.transactionTime)}\n备注：${transaction.remark || '无'}`);
			}
		},
		goToRecharge() {
			this.$router.push('/walletRecharge');
		},
		goBack() {
			this.$router.push('/wallet');
		}
	},
	mounted() {
		this.loadTransactions();
	}
};
</script>

<style scoped>
.wrapper {
	padding-bottom: 60px;
	min-height: 100vh;
	background-color: #f5f5f5;
}

header {
	background-color: #0097ff;
	color: #fff;
	padding: 4vw;
	text-align: center;
}

header p {
	margin: 0;
	font-size: 4.5vw;
	font-weight: 500;
}

/* 筛选条件 */
.filter-section {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 4vw;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filter-group {
	margin-bottom: 3vw;
}

.filter-group:last-child {
	margin-bottom: 0;
}

.filter-group label {
	display: block;
	margin-bottom: 2vw;
	font-size: 3.5vw;
	color: #333;
	font-weight: 500;
}

.filter-group select {
	width: 100%;
	padding: 2vw;
	border: 1px solid #ddd;
	border-radius: 1vw;
	font-size: 3.5vw;
	color: #333;
	background-color: #fff;
}

.custom-date {
	margin-top: 3vw;
	padding-top: 3vw;
	border-top: 1px solid #f0f0f0;
}

.date-group {
	margin-bottom: 2vw;
}

.date-group:last-child {
	margin-bottom: 0;
}

.date-group label {
	display: block;
	margin-bottom: 1vw;
	font-size: 3vw;
	color: #666;
}

.date-group input {
	width: 100%;
	padding: 2vw;
	border: 1px solid #ddd;
	border-radius: 1vw;
	font-size: 3.5vw;
}

/* 交易列表 */
.transactions-list {
	background-color: #fff;
	margin: 0 3vw 3vw 3vw;
	border-radius: 2vw;
	overflow: hidden;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.transaction-item {
	padding: 4vw;
	border-bottom: 1px solid #f0f0f0;
	cursor: pointer;
	transition: background-color 0.3s;
}

.transaction-item:last-child {
	border-bottom: none;
}

.transaction-item:hover {
	background-color: #f8f9fa;
}

.transaction-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 2vw;
}

.transaction-type {
	font-size: 3.5vw;
	color: #333;
	font-weight: 500;
}

.transaction-time {
	font-size: 3vw;
	color: #999;
}

.transaction-content {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
}

.amount-section {
	flex-shrink: 0;
}

.amount {
	font-size: 4.5vw;
	font-weight: bold;
}

.amount.income {
	color: #52c41a;
}

.amount.expense {
	color: #ff4d4f;
}

.transaction-info {
	flex: 1;
	margin-left: 3vw;
}

.remark {
	margin: 0 0 1vw 0;
	font-size: 3vw;
	color: #666;
}

.order-info {
	margin: 0;
	font-size: 3vw;
	color: #999;
}

.transaction-arrow {
	margin-left: 2vw;
}

.transaction-arrow i {
	color: #ccc;
	font-size: 3.5vw;
}

/* 空状态 */
.empty-state {
	text-align: center;
	padding: 10vw 4vw;
	color: #999;
}

.empty-state i {
	font-size: 8vw;
	margin-bottom: 3vw;
	display: block;
}

.empty-state p {
	margin: 0 0 4vw 0;
	font-size: 4vw;
}

.action-btn {
	background-color: #0097ff;
	color: #fff;
	border: none;
	border-radius: 2vw;
	padding: 3vw 6vw;
	font-size: 3.5vw;
	cursor: pointer;
}

.action-btn:hover {
	background-color: #007acc;
}

/* 加载状态 */
.loading {
	text-align: center;
	padding: 6vw;
	color: #666;
	font-size: 4vw;
}

/* 错误提示 */
.error-msg {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 4vw;
	text-align: center;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.error-msg p {
	margin: 0 0 3vw 0;
	color: #ff4d4f;
	font-size: 3.5vw;
}

.error-msg button {
	background-color: #0097ff;
	color: #fff;
	border: none;
	border-radius: 1vw;
	padding: 2vw 4vw;
	font-size: 3.5vw;
	cursor: pointer;
}

.error-msg button:hover {
	background-color: #007acc;
}

/* 后端配置错误样式 */
.error-msg.backend-error {
	background-color: #fff3cd;
	border: 2px solid #ffc107;
}

.error-msg.backend-error p:first-child {
	color: #856404;
	font-weight: bold;
}

.error-msg .error-tip {
	color: #856404;
	font-size: 3vw;
	margin-top: 2vw;
	font-style: italic;
}

/* 返回按钮 */
.back-button {
	margin: 3vw;
}

.back-button button {
	width: 100%;
	background-color: #f5f5f5;
	color: #666;
	border: none;
	border-radius: 2vw;
	padding: 3vw;
	font-size: 4vw;
	cursor: pointer;
}

.back-button button:hover {
	background-color: #e9ecef;
}
</style>
